<?php
require "lib/shape.php";

class ShapeFactory
{
    /**
     * @param string $type
     * @return Shape
     */
    public function getShape($type)
    {
        $type=strtolower($type);
        $shape=null;
        switch ($type) {
            case 'rectangle':
                $shape = new Rectangle;
                break;
            case 'square':
                $shape = new Square;
                break;
            case 'circle':
                $shape = new Circle;
                break;
        }
        return $shape;
    }
}

class ShapeFactoryB
{
    public $map=[[
        "type"=>"",
        "class"=>Shape::class,
    ]];
    public function __construct($map)
    {
        $this->map=$map;
    }
    /**
     * @param string $type
     * @return Shape
     */
    public function getShape($type)
    {
        $type=strtolower($type);
        $shape=null;
        foreach($this->map as $info){
            if($type === $info["type"]){
                $shape = new $info["class"];
                break;
            }
        }
        return $shape;
    }
}

header('Content-Type: text/plain');

/**
 * 工厂模式(误)
 * 实际上是简单工厂模式，不是23中设计模式中的一种
 */
$factory=new ShapeFactory;
$factory->getShape("CIRCLE")->draw();
$factory->getShape("RECTANGLE")->draw();
$factory->getShape("SQUARE")->draw();

//通过映射表指定子类
$factory=new ShapeFactoryB([
    ["type"=>"rectangle","class"=>Rectangle::class],
    ["type"=>"square","class"=>Square::class],
    ["type"=>"circle","class"=>Circle::class],
]);
$factory->getShape("CIRCLE")->draw();
$factory->getShape("RECTANGLE")->draw();
$factory->getShape("SQUARE")->draw();
